package com.example.controller;

import com.example.entity.Result;
import com.example.entity.User;
import com.example.entity.UserDTO;
import com.example.properties.JwtProperties;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
@Slf4j
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    // TODO 没有JWT验证
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userLoginDTO) throws Exception {
        log.info("用户申请登录：{}",userLoginDTO);
        User user = userService.login(userLoginDTO);

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        return Result.success(token);
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) throws Exception {
        int id = userService.exists(userDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId",id);
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        return Result.success(token);
    }
}
